<?php

namespace App\Http\Controllers\api;

use App\Classify;
use App\Comment;
use App\DemandAllureLabel;
use App\DemandArea;
use App\DemandBrowseRecord;
use App\DemandButt;
use App\DemandButtCaseImg;
use App\DemandImg;
use App\Demands;
use App\Http\Services\CommonManager;
use App\Http\Services\FileManager;
use App\Http\Services\UserManager;
use App\Http\Services\Wechat\WechatLogin;
use App\Http\Services\YunPian;
use App\Industries;
use App\Message;
use App\MessageRemind;
use App\SysSetUp;
use App\UnitBusinessLabel;
use App\UnitGrade;
use App\User;
use App\UserAttentionActivity;
use App\UserAttentionDemand;
use App\UserInfo;
use App\VipPackageXRule;
use App\VipRule;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\UserXUnit;
use App\Units;
use Illuminate\Support\Facades\DB;

class DemandController extends Controller
{

    public function getDemandAreaList(Request $request){
        $thatAreaList = DemandArea::where('p_id',"<>",0)->get();

        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$thatAreaList]);
    }

    public function getUnitInfo(Request $request){
        $thatGrades = UnitGrade::orderBy("level","asc")->get();
        if(count($thatGrades) > 0){
            foreach ($thatGrades as $thatGrade){
                $thatUnit = Units::whereUnitGradeId($thatGrade->id)->first();
                if($thatUnit){
                    $thatGrade->content = $thatUnit->introduction;
                }else{
                    $thatGrade->content = "暂无内容";
                }
            }
        }

        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$thatGrades]);
    }

    /**@author cmj
     * 获取需求列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getDemandList(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        $page       =!is_null($request->get('page'))    ? $request->get('page')     : 1;
        $limit      =!is_null($request->get('limit'))   ? $request->get('limit')    : 200;
        $province   =!is_null($request->get('province'))? $request->get('province') : '';
        $city       = !is_null($request->get('city'))   ? $request->get('city')     : '';
        $area       = !is_null($request->get('area'))   ? $request->get('area')     : '';

        $industry_id    =!is_null($request->get('industry_id')) ? $request->get('industry_id') : 0;
        $classify_id    =!is_null($request->get('classify_id')) ? $request->get('classify_id') : 0;
        $is_recommend   =!is_null($request->get('is_recommend'))? $request->get('is_recommend'): 0;
        $is_hot         =!is_null($request->get('is_hot'))      ? $request->get('is_hot')      : 0;
        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page=$page-1;

        $demands=Demands::where("status",">",0)->whereReview(1);

        if ($province)
            $demands=$demands->whereProvince($province);
        if ($city)
            $demands=$demands->whereCity($city);
        if ($area)
            $demands=$demands->whereArea($area);

        if ($industry_id)
            $demands=$demands->whereIndustryId($industry_id);

        if ($classify_id)
            $demands=$demands->whereClassifyId($classify_id);

//        if($user){
//            $demands = $demands->orWhere(function ($query) use($user){
//                $query->whereUserId($user->id)->whereReview(0);
//            });
//        }
        $page_info['total']=$demands->count();

        if($user){
            $userBasicInfo = CommonManager::getUserBasicInfo($user->id);
            $isPersonalAuth = $userBasicInfo ? $userBasicInfo['is_personal_auth'] : 0;
            $isUnitAuth     = $userBasicInfo ? $userBasicInfo['is_unit_auth'] : 0;
            $isExpertAuth   = $userBasicInfo ? $userBasicInfo['is_expert_auth'] : 0;

//            if($isPersonalAuth == 1 || $isUnitAuth == 1 || $isExpertAuth == 1){
            if($isPersonalAuth == 1){
                $demands = $demands->orderBy('is_top','desc');

                if ($is_recommend==1)
                    $demands=$demands->orderBy('attention_num','desc');
//            $demands=$demands->whereIsRecommend(1);
                if ($is_hot==1)
                    $demands=$demands->orderBy('browse_num','desc');
                else
                    $demands=$demands->orderBy('created_at','desc');

                $demands=$demands->offset($page * $limit)->limit($limit)->get();
            }else{
//                if($page_info['total'] > 10){
//                    $page_info['total'] = 10;
//                }

                $demands=$demands->orderBy('created_at','desc')->offset($page * $limit)->limit($limit)->get();
            }
        }else{
//            if($page_info['total'] > 5){
//                $page_info['total'] = 5;
//            }
            $demands=$demands->orderBy('created_at','desc')->offset($page * $limit)->limit($limit)->get();
        }
        $url_array=[];

        if (count($demands) > 0){
            /** @var Demands $demand */
            foreach ($demands as $demand){
                $commentCount =Comment::whereDemandId($demand->id)->whereType('demand')->whereStatus(1)->count();
                if($demand->status == 2 && $commentCount > 0){
                    $demand->status = 3;
                    $demand->save();
                }

                $url_array=[];
                $classify   =Classify::whereId($demand->classify_id)    ->first();
                $industry   =Industries::whereId($demand->industry_id)  ->first();
                $imgs       =DemandImg::whereDemandId($demand->id)      ->get();
                $label      =DemandAllureLabel::whereDemandId($demand->id)->pluck('name')->toArray();

                if (count($imgs) > 0){
                    /** @var DemandImg $img */
                    foreach ($imgs as $img){
                        $url=FileManager::getImgUrl($img->img_id);
                        array_push($url_array,$url);
                    }
                }
                $demand->classify_name  = $classify ? $classify->name :'其他';
                $demand->industry_name  = $industry ? $industry->name :'其他';
                $demand->img_array_url  = $url_array;
                $demand->label_arr      = $label;
                $demand->is_collection  = $user ? (UserAttentionDemand::whereUserId($user->id)->whereDemandId($demand->id)->first() ? 1 :2 ) : 2;

            }
        }
        return response()->json(['level'=>'success','message'=>'获取成功','page_info'=>$page_info,'data'=>$demands]);

    }

    /**@author cmj
     * 获取需求详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getDemandDetail(Request $request){
        $user = UserManager::isLogin($request);

        $id=$request->get('id');
        if (!is_numeric($id))
            return response()->json(['level'=>'error','message'=>'参数错误','data'=>[]]);
        $demand=Demands::whereId($id)->withTrashed()->first();
        if (!$demand)
            return response()->json(['level'=>'error','message'=>'该服务不存在','data'=>[]]);
        if ($demand->deleted_at!=null){
            if($user){
                $userAttackActivity = UserAttentionDemand::whereDemandId($demand->id)->whereUserId($user->id)->first();
                if($userAttackActivity){
                    return response()->json(['level'=>'error','message'=>'该服务已被删除','data' => 1]);
                }else{
                    return response()->json(['level'=>'error','message'=>'该服务已被删除','data' => 2]);
                }
            }else{
                return response()->json(['level'=>'error','message'=>'该服务已被删除','data' => '']);
            }
        }

        if ($demand->review!=1){
            if ($demand->review==2)
                return response()->json(['level'=>'error','message'=>'该服务审核被拒绝','data'=>[]]);
        }

//        if ($demand->is_shop!=1)
//            return response()->json(['level'=>'error','message'=>'该服务已下架','data'=>[]]);


        //TODO 新增浏览记录
        $user_id = $user ? $user->id : 0;
        self::addReadDemandRecord($id,$user_id,$request->ip());

        $classify               =Classify::whereId($demand->classify_id)->first();
        $industry               =Industries::whereId($demand->industry_id)->first();

        $imgs                   =DemandImg::whereDemandId($demand->id)->get();
        $butts                  =DemandButt::whereDemandId($demand->id)->orderBy('created_at','desc')->offset(0)->limit(5)->get();
        $label                  =DemandAllureLabel::whereDemandId($demand->id)->pluck('name')->toArray();
//        $butt_info=[];
        $url_array=[];
        $demand->user_info      =[];
        if ($user_id == $demand->user_id)
            $demand->user_info      = CommonManager::getUserBasicInfo($demand->user_id);

//        if($demand->is_show_publisher == 1)
//            $demand->user_info      = CommonManager::getUserBasicInfo($demand->user_id);

        $buttInfo = [];
        if (count($butts) > 0){
            /** @var DemandButt $butt */
            foreach ($butts as $butt){
                $info=CommonManager::getUserBasicInfo($butt->user_id);
                $butt->user_info=$info ? $info : null;

                if(is_null($butt->business_situation) || $butt->business_situation == ''){
                    $butt->business_situation = null;
                }

                $demandButtCaseImgList = DemandButtCaseImg::whereDemandButtId($butt->id)->get();
                if(count($demandButtCaseImgList) > 0){
                    foreach($demandButtCaseImgList as $demandButtCaseImg){
                        $demandButtCaseImg->img_url = FileManager::getImgUrl($demandButtCaseImg->img_id);
                    }
                }

                $butt->case_img_list = $demandButtCaseImgList;
//                if ($info)
//                    array_push($butt_info,$info);

                if ($user_id && $user_id == $butt->user_id && $butt->status ==1 )
                    $demand->user_info      = CommonManager::getUserBasicInfo($demand->user_id);

                if($butt->status == 1){
                    $statusName = '对接成功';
                }elseif($butt->status == 2){
                    $statusName = '淘汰';
                }else{
                    $statusName = '筛选中';
                }

                if($demand->status != 1){
                    if($user_id && $user_id == $demand->user_id){
                        $butt->status_name = $statusName;

//                        array_push($buttInfo,$butt);
                    }else{
                        if($user_id && $user_id == $butt->user_id){
                            $butt->status_name = $statusName;

//                            array_push($buttInfo,$butt);
                        }
                    }
                }else{
                    $butt->status_name = $statusName;
                }


            }
        }



        if (count($imgs) > 0){
            foreach ($imgs as $img){
                $url=FileManager::getImgUrl($img->img_id);
                array_push($url_array,$url);
            }
        }

        $demand->is_submit_butt = 0;
        $demand_butt= DemandButt::whereDemandId($demand->id)->whereUserId($user_id)->first();
        if($demand_butt){
            $demand->is_submit_butt = 1;
        }

        $demand->classify_name  = $classify ? $classify->name :'其他';
        $demand->industry_name  = $industry ? $industry->name :'其他';
        $demand->img_array_url  = $url_array;
        $demand->butt_info      = $butts;
//        $demand->user_info      = CommonManager::getUserBasicInfo($demand->user_id);
        $demand->label_arr      = $label;
        $demand->is_collection  = $user ? (UserAttentionDemand::whereUserId($user->id)->whereDemandId($demand->id)->first() ? 1 :2 ) : 2;
        $demand->butting_num    = DemandButt::whereDemandId($demand->id)->count();

        $DemandButtImgArr = [];
        /** @var DemandButt $DemandButtImg */
        $DemandButtImgList = DemandButt::whereDemandId($demand->id)->take(3)->get();
        if($DemandButtImgList){
            foreach($DemandButtImgList as $DemandButtImg){
                $userInfo = CommonManager::getUserBasicInfo($DemandButtImg->user_id);
                array_push($DemandButtImgArr,$userInfo ? $userInfo['photo_url'] : '');
            }
        }

        $demand->demand_butt_img_list    = $DemandButtImgArr;

        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$demand]);
    }

    /**@author cmj
     * 获取我发布的需求
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMyDemandInfo(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $page       =!is_null($request->get('page'))    ? $request->get('page')     : 1;
        $limit      =!is_null($request->get('limit'))   ? $request->get('limit')    : 10;
        $status     =!is_null($request->get('status'))  ? $request->get('status')   : 0;
        $review     =!is_null($request->get('review'))  ? $request->get('review')   : 0;

        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page=$page-1;
        $demands=Demands::whereUserId($user->id)->orderBy('created_at','desc');
        //数据库status的值为0，1，因不传与传0难以区分，故将0替换为2；
        if ($status==1)
            $demands=$demands->whereStatus(1);
        else if ($status==2)
            $demands=$demands->whereStatus(0);

        if($review == 3){
            $demands = $demands->whereReview(0);
        }

        $page_info['total']=$demands->count();
        $demands=$demands->offset($limit * $page)->limit($limit)->get();
        if (count($demands) > 0){
            /** @var Demands $demand */
            foreach ($demands as $demand){
                $butts=DemandButt::whereDemandId($demand->id)->orderBy('created_at','desc')->offset(0)->limit(2)->get();
                if (count($butts) > 0){
                    /** @var DemandButt $buff */
                    foreach ($butts as $buff){
                        $buff->user_info=CommonManager::getUserBasicInfo($buff->user_id);
                        $buff->join_time=CommonManager::getPublishTime($buff->created_at);

                        if(is_null($buff->business_situation) || $buff->business_situation == ''){
                            $buff->business_situation = null;
                        }

                        $demandButtCaseImgList = DemandButtCaseImg::whereDemandButtId($buff->id)->get();
                        if(count($demandButtCaseImgList) > 0){
                            foreach($demandButtCaseImgList as $demandButtCaseImg){
                                $demandButtCaseImg->img_url = FileManager::getImgUrl($demandButtCaseImg->img_id);
                            }
                        }

                        $buff->case_img_list = $demandButtCaseImgList;
                    }
                }
                $demand->buff=$butts;
                $demand->is_collection  = $user ? (UserAttentionDemand::whereUserId($user->id)->whereDemandId($demand->id)->first() ? 1 :2 ) : 2;

                if($demand->review == 1){
                    if($demand->status == 1){
                        $demand->status_name = '成功对接';
                    }else{
                        $demand->status_name = '正在筛选中';
                    }
                }elseif($demand->review == 2){
                    $demand->status_name = '审核失败';
                }else{
                    $demand->status_name = '审核中';
                }
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功！','page_info'=>$page_info,'data' => $demands]);

    }

    /**@author cmj
     * 获取对接我需求的用户信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMyDemandButtDetail(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $demand_id  =$request->get('demand_id');
        $user_id    =$request->get('user_id');
//        $demand=Demands::whereId($demand_id)->whereUserId($user->id)->whereReview(1)->first();
        $demand=Demands::whereId($demand_id)->whereReview(1)->first();
        if (!$demand)
            return response()->json(['level' => 'error','message' => '服务不存在！','data' => []]);
        $butt=DemandButt::whereDemandId($demand_id)->whereUserId($user_id)->first();
        if (!$butt)
            return response()->json(['level' => 'error','message' => '查看的用户并没有参与对接！','data' => []]);

        if(is_null($butt->business_situation) || $butt->business_situation == ''){
            $butt->business_situation = null;
        }

        $demandButtCaseImgList = DemandButtCaseImg::whereDemandButtId($butt->id)->get();
        if(count($demandButtCaseImgList) > 0){
            foreach($demandButtCaseImgList as $demandButtCaseImg){
                $demandButtCaseImg->img_url = FileManager::getImgUrl($demandButtCaseImg->img_id);
            }
        }

        $butt->case_img_list = $demandButtCaseImgList;

        $buff_info=CommonManager::getUserBasicInfo($user_id);
        if($buff_info){
            $unit = Units::whereId($butt->unit_id)->first();
            if($unit){
                //单位名称
                $buff_info['unit_logo']    = FileManager::getImgUrl($unit->photo_id);
                $buff_info['unit_name']    = $unit->name;
                $buff_info['unit_contact']     = $unit->contact_number ? $unit->contact_number : $unit->contact_phone;
                $buff_info['unit_credit_code'] = $unit->uniform_social_credit_code;
                $buff_info['unit_label']       = UnitBusinessLabel::whereUnitId($unit->id)->pluck('name')->toArray();
                $buff_info['unit_province']    = $unit->province;
                $buff_info['unit_city']        = $unit->city;
                $buff_info['unit_area']        = $unit->area;
                $buff_info['unit_address']     = $unit->address;

            }
        }
        $buff_info['status']=$butt->status;
        $buff_info['butt_info'] = $butt;
        return response()->json(['level' => 'success','message' => '获取成功','data' => $buff_info]);

    }

    /**@author cmj
     * 获取我对接的需求
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMyJoinDemandInfo(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $page       =!is_null($request->get('page'))    ? $request->get('page')     : 1;
        $limit      =!is_null($request->get('limit'))   ? $request->get('limit')    : 10;
        $status     =!is_null($request->get('status'))  ? $request->get('status')   : 0;

        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page=$page-1;
        //数据库status的值为0，1,2，因不传与传0难以区分，故将0替换为3；
        $demand_ids=DemandButt::whereUserId($user->id)->orderBy('created_at','desc');
        if ($status==1)
            $demand_ids=$demand_ids->whereStatus(1);
        if ($status==2)
            $demand_ids=$demand_ids->whereStatus(2);
        if ($status==3)
            $demand_ids=$demand_ids->whereStatus(0);

        $page_info['total'] =$demand_ids->count();
        $demand_ids         =$demand_ids->offset($page * $limit)->limit($limit)->pluck('demand_id')->toArray();
        $demands=Demands::whereIn('id',$demand_ids)->withTrashed()->get();
        if (count($demands)>0){
            foreach ($demands as $demand){
                if ($demand->status==1){
                    $is_me=DemandButt::whereUserId($user->id)->whereDemandId($demand->id)->whereStatus(1)->first();
                    $demand->my_status=$is_me ? 1 : 2;
                } else {
                    $demand->my_status=0;
                    $my_tatus=DemandButt::whereUserId($user->id)->whereDemandId($demand->id)->first();
                    $demand->my_status=$my_tatus ? $my_tatus->status : 0;
                }
                $url_array=[];
                $classify   =Classify::whereId($demand->classify_id)    ->first();
                $industry   =Industries::whereId($demand->industry_id)  ->first();
                $imgs       =DemandImg::whereDemandId($demand->id)      ->get();
                $label      =DemandAllureLabel::whereDemandId($demand->id)->pluck('name')->toArray();

                if (count($imgs) > 0){
                    /** @var DemandImg $img */
                    foreach ($imgs as $img){
                        $url=FileManager::getImgUrl($img->img_id);
                        array_push($url_array,$url);
                    }
                }
                $demand->classify_name  = $classify ? $classify->name :'其他';
                $demand->industry_name  = $industry ? $industry->name :'其他';
                $demand->img_array_url  = $url_array;
                $demand->label_arr      = $label;
                $demand->is_collection  = $user ? (UserAttentionDemand::whereUserId($user->id)->whereDemandId($demand->id)->first() ? 1 :2 ) : 2;


            }
        }

        return response()->json(['level' => 'success','message' => '获取成功！','page_info'=>$page_info,'data' => $demands]);

    }

    /**@author cmj
     * 获取需求发布者的信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getDemandSenderInfo(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
//        if(!$user)
//            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $demand_id=$request->get('demand_id');

        $user_id=$request->get('user_id');
        $demand=Demands::whereId($demand_id)->first();
        if ($user_id!=$demand->user_id)
            return response()->json(['level' => 'error','message' => '系统错误！','data' => []]);

        $sender_info=CommonManager::getUserBasicInfo($user_id);
        if($sender_info){
            $unit = Units::whereId($demand->unit_id)->first();
            if($unit){
                //单位名称
                $sender_info['unit_logo']    = FileManager::getImgUrl($unit->photo_id);
                $sender_info['unit_name']    = $unit->name;
                $sender_info['unit_contact']     = $unit->contact_number ? $unit->contact_number : $unit->contact_phone;
                $sender_info['unit_credit_code'] = $unit->uniform_social_credit_code;
                $sender_info['unit_label']       = UnitBusinessLabel::whereUnitId($unit->id)->pluck('name')->toArray();
                $sender_info['unit_province']    = $unit->province;
                $sender_info['unit_city']        = $unit->city;
                $sender_info['unit_area']        = $unit->area;
                $sender_info['unit_address']     = $unit->address;
            }
        }
        return response()->json(['level' => 'success','message' => '获取成功','data' => $sender_info]);
    }

    /**@author cmj
     * 操作（淘汰、接受）对接者
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function operateDemandJoiner(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $demand_id  =$request->get('demand_id');
        $user_id    =$request->get('user_id');
        $type       =$request->get('type');

        $demand=Demands::whereId($demand_id)->first();
        if ($user->id!=$demand->user_id)
            return response()->json(['level' => 'error','message' => '系统错误！','data' => []]);

        $demand_butt=DemandButt::whereDemandId($demand_id)->whereUserId($user_id)->whereStatus(0)->first();
        if (!$demand_butt)
            return response()->json(['level'=>'error','message'=>'已经操作过了','data'=>[]]);
        $demand_img_id= DemandImg::whereDemandId($demand_id)->first();

        if ($type==1){
            $demand->status=1;
            $demand->save();
            $demand_butt->status=1;
            $demand_butt->success_time = date("Y-m-d H:i:s",time());
            $demand_butt->save();

            $message=new Message();
            $message->title     ='恭喜你，对接成功';
            $message->content   ='您请求对接的需求【'.$demand->title.'】已成功对接，请尽快联系发布方洽谈！';
            $message->to_user_id=$demand_butt->user_id;
            $message->demand_id =$demand_id;
            $message->img_id    = $demand_img_id ? $demand_img_id->img_id : 0;
            $message->type      = 'demand';
            $message->save();

            $message_remind             = new MessageRemind();
            $message_remind->user_id    = $demand_butt->user_id;
            $message_remind->message_id = $message->id;
            $message_remind->save();

            $message=new Message();
            $message->title     ='恭喜你，对接成功';
            $message->content   ='您发布的服务【'.$demand->title.'】已成功对接，请尽快联系对接方洽谈！';
            $message->to_user_id=$demand->user_id;
            $message->demand_id =$demand_id;
            $message->img_id    = $demand_img_id ? $demand_img_id->img_id : 0;
            $message->type      = 'demand';
            $message->save();

            $message_remind             = new MessageRemind();
            $message_remind->user_id    = $demand->user_id;
            $message_remind->message_id = $message->id;
            $message_remind->save();

            $buttUser = User::whereId($demand_butt->user_id)->first();
            if($buttUser){
                $realname = '';
                $userInfo = UserInfo::whereUserId($demand->user_id)->first();
                if($userInfo){
                    if(empty($userInfo->realname)){
                        $realname = $userInfo->nickname;
                    }else{
                        $realname = $userInfo->realname;
                    }
                }

                $send = new YunPian();
                $send->sendSms($buttUser->phone,stripslashes("【省人协】\\" . "{$realname}同意你的对接请求了！"));
            }

            $r = WechatLogin::weSendDemandMessage($buttUser->wx_openid,"/pages/details/needsDetail/needsDetail?needsId=".$demand->id,$demand->title,"通过");

            return response()->json(['level'=>'success','message'=>'接受成功','data'=>'success',"r"=>$r]);
        } else if ($type==2){
//            $demand->status=2;
//            $demand->save();
            $demand_butt->status=2;
            $demand_butt->success_time = date("Y-m-d H:i:s",time());
            $demand_butt->save();

            $message=new Message();
            $message->title     ='很遗憾，您的对接请求已被拒绝';
            $message->content   ='您请求对接的服务【'.$demand->title.'】已被拒绝！';
            $message->to_user_id=$demand_butt->user_id;
            $message->demand_id =$demand_id;
            $message->img_id    =$demand_img_id ? $demand_img_id : 0;;
            $message->type      = 'demand';
            $message->save();

            $message_remind             = new MessageRemind();
            $message_remind->user_id    = $demand_butt->user_id;
            $message_remind->message_id = $message->id;
            $message_remind->save();

            $buttUser = User::whereId($demand_butt->user_id)->first();

            $r = WechatLogin::weSendDemandMessage($buttUser->wx_openid,"/pages/details/needsDetail/needsDetail?needsId=".$demand->id,$demand->title,"不通过");

            return response()->json(['level'=>'success','message'=>'淘汰成功','data'=>'success',"r"=>$r]);
        } else {
            return response()->json(['level'=>'error','message'=>'参数type错误','data'=>'error']);
        }

    }

    /**@author cmj
     *手机端发布需求
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function sendDemandByPhone(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $title                 =$request->get('title');
        $content               =$request->get('content');
        $recruitment           =$request->get('recruitment');
        $salary                =$request->get('salary');
        $education             =$request->get('education');
        $first_arrive_time     =$request->get('first_arrive_time');
        $last_arrive_time      =$request->get('last_arrive_time');
        $start_time            =$request->get('start_time');
        $end_time              =$request->get('end_time');
        $classify_id           =$request->get('classify_id');
        $province              =$request->get('province');
        $city                  =$request->get('city');
        $area                  =$request->get('area');
        $address               =$request->get('address');
        $industry              =$request->get('industry_id');
        $img_ids               =$request->get('img_ids');
        $label_arr             =$request->get('label_arr');
        $demandType            =$request->get('demand_type');
        $is_show_publisher     =!is_null($request->get('is_show_publisher')) ? $request->get('is_show_publisher') : 0;
        $isAssociationDocking  =!is_null($request->get('is_association_docking')) ? $request->get('is_association_docking') : 0;
        $maxButtingNum         =!is_null($request->get('max_butting_num')) ? $request->get('max_butting_num') : 0;
        $budget                =!is_null($request->get('budget')) ? $request->get('budget') : '';

        if (!$demandType)
            return response()->json(['level' => 'error','message' => '请选择所属会客室','data' => []]);

        if (!$classify_id)
            return response()->json(['level' => 'error','message' => '请选择类型','data' => []]);
        if (!$title)
            return response()->json(['level' => 'error','message' => '请输入标题','data' => []]);
        if (!$content)
            return response()->json(['level' => 'error','message' => '请输入内容','data' => []]);

//        if(!$province)
//            return response()->json(['level' => 'error','message' => '请选择所在地区','data' => []]);

//        if(!$city)
//            return response()->json(['level' => 'error','message' => '请选择所在地区','data' => []]);
//
//        if(!$area)
//            return response()->json(['level' => 'error','message' => '请选择所在地区','data' => []]);
//        if (!$industry)
//            return response()->json(['level' => 'error','message' => '请选择所在行业','data' => []]);

        $demand=Demands::whereUserId($user->id)->whereTitle($title)->whereStatus(0)->first();
        if ($demand)
            return response()->json(['level' => 'error','message' => '重复发布','data' => []]);

        //是否有发布需求权益
//        $releaseDemand = 3;
//        $releaseDemandVipRule = VipRule::whereMark('release_demand')->first();
//        if($releaseDemandVipRule){
//            $userBindVipPackageList = CommonManager::judgeVipPackageXRule($releaseDemandVipRule->id,$user->id);
//            if($userBindVipPackageList){
//                $releaseDemand = 0;
//                $userBindVipPackageList = CommonManager::getUserBindVipPackageInfo($user->id);
//                if(count($userBindVipPackageList) > 0){
//                    foreach($userBindVipPackageList as $userBindVipPackage){
//                        if(!empty($userBindVipPackage->vip_package_info)){
//                            $vipPackageXRule = VipPackageXRule::whereVipPackageId($userBindVipPackage->vip_package_info->id)->whereVipRuleId($releaseDemandVipRule->id)->first();
//                            if($vipPackageXRule){
//                                $releaseDemand += $vipPackageXRule->today_run_num;
//                            }
//                        }
//                    }
//                }
//            }
//        }

        //每日开始时间和结结束时间
//        $todayStartTime = date("Y-m-d 00:00:00",time());
//        $todayEndTime   = date("Y-m-d 23:59:59",time());

//        $todayReleaseDemandNum = Demands::whereUserId($user->id)->whereBetween('created_at',[$todayStartTime,$todayEndTime])->count();
//        if($todayReleaseDemandNum >= $releaseDemand)
//            return response()->json(['level' => 'error','message' => '发布次数已用尽']);

//        $isunitAuth = CommonManager::isUnitAuth($user->id);
//        if(!$isunitAuth)
//            return response()->json(['level' => 'error','message' => '请先进行单位认证']);

        $UserXUnit = UserXUnit::whereUserId($user->id)->first();
//        if(!$UserXUnit)
//            return response()->json(['level' => 'error','message' => '系统错误']);
        if ($UserXUnit)
            $unit = Units::whereId($UserXUnit->unit_id)->first();
        else $unit=0;
//        if(!$unit)
//            return response()->json(['level' => 'error','message' => '单位不存在']);


        //判断是否优先审核
        $isPriorityReview = 0;
        $priorityReviewVipRule = VipRule::whereMark('priority_review')->first();
        if($priorityReviewVipRule){
            $userBindVipPackageList = CommonManager::judgeVipPackageXRule($priorityReviewVipRule->id,$user->id);
            if($userBindVipPackageList){
                $isPriorityReview = 1;
            }
        }

        $demand=new Demands();
        $demand->user_id            =$user->id;
        if ($unit)
            $demand->unit_id            =$unit->id;
        $demand->is_show_publisher  =$is_show_publisher ? 1 :0;
        $demand->is_association_docking = $isAssociationDocking ? 1 : 0;
        if ($title)
            $demand->title          =$title;
        if ($content)
            $demand->content        =$content;
        if ($recruitment)
            $demand->recruitment    =$recruitment;
        if ($salary)
            $demand->salary         =$salary;
        if ($education)
            $demand->education      =$education;
        if ($first_arrive_time)
            $demand->first_arrive_time  =$first_arrive_time;
        if ($last_arrive_time)
            $demand->last_arrive_time   =$last_arrive_time;
        if ($start_time)
            $demand->start_time         =$start_time;
        if ($end_time)
            $demand->end_time           =$end_time;
        if ($classify_id)
            $demand->classify_id        =$classify_id;
        if ($province)
            $demand->province           =$province;
        if ($city)
            $demand->city               =$city;
        if ($area)
            $demand->area               =$area;
        if ($address)
            $demand->address            =$address;
        if ($industry)
            $demand->industry_id        =$industry;
        if ($demandType)
            $demand->demand_type        =$demandType;
        if($isPriorityReview == 1)
            $demand->is_top             =1;

        if($maxButtingNum)
            $demand->max_butting_num        = $maxButtingNum;

        $demand->budget                 = $budget;

        $demand->save();
        if (count($img_ids) > 0){
            foreach ($img_ids as $img_id) {
                $exist=DemandImg::whereDemandId($demand->id)->whereImgId($img_id)->first();
                if(!$exist){
                    $demand_img = new DemandImg();
                    $demand_img->demand_id = $demand->id;
                    $demand_img->img_id = $img_id;
                    $demand_img->save();
                }
            }
        }
        if (count($label_arr) > 0){
            foreach ($label_arr as $label){
                $label_exist=DemandAllureLabel::whereName($label)->whereDemandId($demand->id)->first();
                if (!$label_exist){
                    $thisDemandLabel          =new DemandAllureLabel();
//                $thisNewsLabel->user_id=0;
                    $thisDemandLabel->name      =$label;
                    $thisDemandLabel->demand_id =$demand->id;
                    $thisDemandLabel->save();
                }
            }
        }

        $userInfo = CommonManager::getUserBasicInfo($user->id);
        $realname = !empty($userInfo['realname']) ? $userInfo['realname'] : $userInfo['nickname'];

        $newMessage = new Message();
        $newMessage->type        = 'admin';
        $newMessage->content     = $realname . "发布了【{$demand->title}】，请尽快审核";
        $newMessage->link_type   = 'service';
        $newMessage->link_id     = $demand->id;
        $newMessage->save();

        return response()->json(['level' => 'success','message' => '已提交审核','data' => $demand]);
    }

    public function favoriteDemand(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $demand_id  =$request->get('demand_id');
        if (!$demand_id)
            return response()->json(['level'=>'error','message'=>'参数错误']);

        $is_favorite=UserAttentionDemand::whereUserId($user->id)->whereDemandId($demand_id)->first();
        if ($is_favorite){
            return response()->json(['level' => 'success','message' => '已经关注过了！','data' =>'is_favorite']);
        }

        $demand=Demands::whereId($demand_id)->whereReview(1)->first();
        if (!$demand)
            return response()->json(['level'=>'error','message'=>'服务不存在']);

        $new_favorite = new UserAttentionDemand();
        $new_favorite->user_id  =$user->id;
        $new_favorite->demand_id=$demand_id;
        $new_favorite->save();
        $demand->attention_num=UserAttentionDemand::whereDemandId($demand_id)->count();
        $demand->save();

        return response()->json(['level' => 'success','message' => '关注成功！','data' =>'is_favorite']);

    }

    public function unFavoriteDemand(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $demand_id  =$request->get('demand_id');

        $is_favorite=UserAttentionDemand::whereUserId($user->id)->whereDemandId($demand_id)->first();
        if (!$is_favorite){
            return response()->json(['level' => 'success','message' => '还没关注哦！','data' =>'not_favorite']);
        }
        $is_favorite->delete();
        $demand=DB::table('demands')->whereId($demand_id)->whereReview(1)->first();
        if ($demand){
            $attention_num=UserAttentionDemand::whereDemandId($demand_id)->count();
            DB::table('demands')->where('id',$demand_id)->update(['attention_num' => $attention_num]);
        }

        return response()->json(['level' => 'success','message' => '取消关注成功！','data' =>'not_favorite']);
    }

    public function getDemandIndex(Request $request)
    {
        $demand_butt = DemandButt::orderBy('updated_at', 'desc')->offset(0)->limit(5)->get();
        if (count($demand_butt) > 0) {
            /** @var DemandButt $item */
            foreach ($demand_butt as $item) {
                $userXUnit  = UserXUnit::whereUserId($item->user_id)->first();
                if ($userXUnit) {
                    $unit       = Units::whereId($userXUnit->unit_id)->first();
                } else {
                    $unit=[];
                }
                $demand_info=Demands::whereId($item->demand_id)->first();
                $item->unit_name    = $userXUnit    ? $unit->name : '***公司';
                $item->status_name  = $item->status ? '成功对接' : '申请对接';
                $item->demand_name  = $demand_info  ? $demand_info->title : '新需求';


//                if(is_null($item->business_situation) || $item->business_situation == ''){
//                    $item->business_situation = null;
//                }
//
//                $demandButtCaseImgList = DemandButtCaseImg::whereDemandButtId($item->id)->get();
//                if(count($demandButtCaseImgList) > 0){
//                    foreach($demandButtCaseImgList as $demandButtCaseImg){
//                        $demandButtCaseImg->img_url = FileManager::getImgUrl($demandButtCaseImg->img_id);
//                    }
//                }

//                $item->case_img_list = $demandButtCaseImgList;
            }

        }
        return response()->json(['level'=>'success','message'=>'success','data'=>$demand_butt]);

    }
    public function joinDemand(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $demand_id         = $request->get('demand_id');
        $caseImgIds        = $request->get('case_img_ids');
        $businessSituation = $request->get('business_situation');
        $phone    = $request->get('phoneNumber');
        $weChat   = $request->get('wechat_Number');
        $email    = $request->get('E_mail');

        if(is_null($phone) || $phone == '')
            return response()->json(['level' => 'error','message' => '请填写手机号']);

        $isPHone = CommonManager::phoneVerification($phone);
        if(!$isPHone)
            return response()->json(['level' => 'error','message' => '请填写手机号']);

        if(is_null($weChat) || $weChat == '')
            return response()->json(['level' => 'error','message' => '请填写微信号']);

        if(is_null($email) || $email == '')
            return response()->json(['level' => 'error','message' => '请填写邮箱']);

        $isEmail = CommonManager::emailVerification($email);
        if(!$isEmail)
            return response()->json(['level' => 'error','message' => '邮箱格式不正确']);

        $user       = User::whereId($user->id)->whereStatus(1)->first();
        $user_info  = UserInfo::whereUserId($user->id)->first();
        if (!$user_info || !$user)
            return response()->json(['level'=>'error','message'=>'您的信息异常','data'=>[]]);
        $has_unit   = CommonManager::isUnitAuth($user->id);
        if (!$has_unit)
            return response()->json(['level'=>'error','message'=>'您需要完成个人认证能对接服务,是否立即前往','data'=>[]]);

        $UserXUnit = UserXUnit::whereUserId($user->id)->first();
        if(!$UserXUnit)
            return response()->json(['level' => 'error','message' => '系统错误']);

        $unit = Units::whereId($UserXUnit->unit_id)->first();
        if(!$unit)
            return response()->json(['level' => 'error','message' => '单位不存在']);

        if(!is_array($caseImgIds) || (is_array($caseImgIds) && count($caseImgIds) <= 0))
            return response()->json(['level' => 'error','message' => '请传入成功案例']);

        //是否有发布需求权益
        $buttDemand = 3;
        $buttDemandVipRule = VipRule::whereMark('release_demand')->first();
        if($buttDemandVipRule){
            $userBindVipPackageList = CommonManager::judgeVipPackageXRule($buttDemandVipRule->id,$user->id);
            if($userBindVipPackageList){
                $buttDemand = 0;
                $userBindVipPackageList = CommonManager::getUserBindVipPackageInfo($user->id);
                if(count($userBindVipPackageList) > 0){
                    foreach($userBindVipPackageList as $userBindVipPackage){
                        if(!empty($userBindVipPackage->vip_package_info)){
                            $vipPackageXRule = VipPackageXRule::whereVipPackageId($userBindVipPackage->vip_package_info->id)->whereVipRuleId($buttDemandVipRule->id)->first();
                            if($vipPackageXRule){
                                $buttDemand += $vipPackageXRule->today_run_num;
                            }
                        }
                    }
                }
            }
        }

        //每日开始时间和结结束时间
        $todayStartTime = date("Y-m-d 00:00:00",time());
        $todayEndTime   = date("Y-m-d 23:59:59",time());

        $todayButtDemandNum = DemandButt::whereUserId($user->id)->whereBetween('created_at',[$todayStartTime,$todayEndTime])->count();
        if($todayButtDemandNum >= $buttDemand)
            return response()->json(['level' => 'error','message' => '对接次数已用尽']);

        $demand_butt= DemandButt::whereDemandId($demand_id)->whereUserId($user->id)->first();
        $demand     = Demands::whereId($demand_id)->whereIsShop(1)->whereReview(1)->first();
        $demand_img_id= DemandImg::whereDemandId($demand_id)->first();
        if (!$demand)
            return response()->json(['level'=>'error','message'=>'您申请对接的服务不存在']);

        $demandButtNum = DemandButt::whereDemandId($demand_id)->count();
        if($demand->max_butting_num > 0 && $demand->max_butting_num <= $demandButtNum)
            return response()->json(['level' => 'error','message' => '对接人数已满']);

//        if ($demand->status==1)
//            return response()->json(['level'=>'error','message'=>'您申请的服务已完成对接']);
        if ($demand_butt && $demand_butt->status == 0)
            return response()->json(['level'=>'error','message'=>'你已经申请过了']);

        if($demand_butt && $demand_butt->status == 2)
            return response()->json(['level'=>'error','message'=>'你已经倍淘汰了']);

        $demand_butt= new DemandButt();
        $demand_butt->demand_id =$demand_id;
        $demand_butt->unit_id   =$unit->id;
        $demand_butt->user_id   =$user->id;
        $demand_butt->phone   = $phone;
        $demand_butt->wechat  = $weChat;
        $demand_butt->email   = $email;
        if($businessSituation)
            $demand_butt->business_situation   = $businessSituation;
        $demand_butt->save();

        $demandButtCaseImgList = DemandButtCaseImg::whereDemandButtId($demand_butt->id)->get();
        if(count($demandButtCaseImgList) > 0){
            foreach($demandButtCaseImgList as $demandButtCaseImg){
                $demandButtCaseImg->forceDelete();
            }
        }

        foreach($caseImgIds as $caseImgId){
            $newDemandButtCaseImg = New DemandButtCaseImg();
            $newDemandButtCaseImg->demand_butt_id     = $demand_butt->id;
            $newDemandButtCaseImg->img_id             = $caseImgId;
            $newDemandButtCaseImg->save();
        }

        $message            = new Message();
        $message->title     = $user_info->realname.'请求对接您的服务！';
        $message->content   = '您发布的需求【'.$demand->title.'】有人来申请对接了，请尽快确认';
        $message->to_user_id= $demand->user_id;
        $message->demand_id = $demand->id;
        $message->img_id    = $demand_img_id ? $demand_img_id : 0;
        $message->type      = 'demand';
        $message->save();

        $message_remind             = new MessageRemind();
        $message_remind->user_id    =$demand->user_id;
        $message_remind->message_id =$message->id;
        $message_remind->save();

        $demandUser = User::whereId($demand->user_id)->first();
        if($demandUser){
            $demandUserInfo = UserInfo::whereUserId($demandUser->id)->first();
            if($demandUserInfo){
                $realname = !empty($user_info->realname) ? $user_info->realname : !empty($user_info->nickname) ? $user_info->nickname : '';
                $send = new YunPian();
                $send->sendSms($demandUser->phone,stripslashes("【省人协】\\" . "{$realname}请求对接您的服务！"));
            }
        }



        return response()->json(['level'=>'success','message'=>'已提交对接申请','data'=>$demand_butt]);

    }

    public function getStatement(){
        $statement=SysSetUp::whereType(2)->whereStatus(1)->orderBy('created_at','desc')->first();
        return response()->json(['level'=>'success','message'=>'success','data'=>$statement]);
    }

    public function getTermsService(){
        $statement=SysSetUp::whereType(5)->whereStatus(1)->orderBy('created_at','desc')->first();

        return response()->json(['level'=>'success','message'=>'success','data'=>$statement]);
    }

    protected function addReadDemandRecord($demand_id,$user_id=0,$ip=null){
        if (!$user_id)
            return 0;
        $demand=Demands::whereId($demand_id)->first();
        $demand_record=DemandBrowseRecord::whereDemandId($demand_id)->whereUserId($user_id)->orderBy('created_at','desc')->first();
        if ($demand_record){
            if (strtotime($demand_record->created_at) + 300 <= time() ){
                $demand_record=new DemandBrowseRecord();
                if ($user_id)
                    $demand_record->user_id =$user_id;
                if ($ip)
                    $demand_record->ip      =$ip;
                $demand_record->demand_id=$demand_id;
                $demand_record->save();
                if ($demand){
                    $demand->browse_num=$demand->browse_num+1;
                    $demand->save();
                }
            }
        } else {
            $demand_record=new DemandBrowseRecord();
            if ($user_id)
                $demand_record->user_id =$user_id;
            if ($ip)
                $demand_record->ip      =$ip;
            $demand_record->demand_id=$demand_id;
            $demand_record->save();
            if ($demand){
                $demand->browse_num=$demand->browse_num+1;
                $demand->save();
            }
        }
        return 1;
    }
}
